package com.kakame.codenews.front.index.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.kakame.codenews.base.constant.SystemConstant;
import com.kakame.codenews.base.util.DESUtil;
import com.kakame.codenews.base.util.EmailUtil;
import com.kakame.codenews.base.util.EncryptUtil;
import com.kakame.codenews.base.util.SessionUtil;
import com.kakame.codenews.base.web.controller.BaseController;
import com.kakame.codenews.base.web.entity.Result;
import com.kakame.codenews.base.web.fast.mapping.common.User;
import com.kakame.codenews.front.index.service.FrontIndexService;
import com.kakame.codenews.front.user.service.FrontUserService;

/**
 * <pre>
 * <b>desc:</b> 前台首页相关控制器 
 * <b>auth:</b> ex-hejm
 * <b>date:</b> 2018年6月8日 下午1:37:30
 * </pre>
 */
@Controller
public class FrontIndexController extends BaseController {
    
    @Resource
    private FrontIndexService indexService;
    @Resource
    private FrontUserService userService;
    
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    
    /**
     * <pre>
     * <b>desc:</b> 前台首页 
     * <b>auth:</b> 何家明
     * <b>date:</b> 2018年6月1日 下午2:17:27
     * </pre>
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "front/index";
    }
    
    /**
     * 跳转到登录页面
     * @author 何家明 2018年7月8日 上午12:19:07
     * @return
     */
    @RequestMapping("/loginPage")
    public String loginPage(ModelMap modelMap) {
    	modelMap.put("menuCode", "login");
        return "front/login";
    }
    /**
     * 跳转到注册页面
     * @author 何家明 2018年7月8日 上午12:19:07
     * @return
     */
    @RequestMapping("/registerPage")
    public String registerPage(ModelMap modelMap) {
    	modelMap.put("menuCode", "register");
    	return "front/register";
    }
    
    /**
     * <pre>
     * <b>desc:</b> 从记住我登录 
     * <b>auth:</b> ex-hejm
     * <b>date:</b> 2018年7月17日 下午5:29:25
     * </pre>
     * @param json
     * @param session
     * @return
     */
    @RequestMapping("/autoLogin")
    @ResponseBody
    public Result autoLogin(@RequestBody String json, HttpSession session) {
        Result result = null;
        
        JSONObject jsonObject = convertJsonToObject(json);
        String userToken = jsonObject.getString("userToken");
        String[] userInfo = DESUtil.getDecryptString(userToken).split(DESUtil.SPLITER);
        String userAccount = userInfo[0];
        String userPwd = userInfo[1];
        User user = User.create().userAccount(userAccount).userPwd(userPwd).build();
        User dbUser = userService.get(user);
        if(StringUtils.equals(userAccount, dbUser.getUserAccount()) && StringUtils.equals(userPwd, dbUser.getUserPwd())) {
            setSession(session, SystemConstant.SESSION_KEY_OF_USER, dbUser);
            result = Result.create().setMsg("登录成功").setStatus(SystemConstant.SUCCESS).build();
        } else {
            result = Result.create().setMsg("登录失败").setStatus(SystemConstant.ERROR).build();
        }
        return result;
    }
    
    /**
     * <pre>
     * <b>desc:</b> 用户登录 
     * <b>auth:</b> 何家明
     * <b>date:</b> 2018年6月6日 上午10:39:17
     * </pre>
     * @param json
     * @param session
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(@RequestBody String json, HttpSession session) {
        String captcha = getSessionString(session, SystemConstant.SESSION_KEY_OF_CAPTCHA);
        JSONObject jsonObject = convertJsonToObject(json);
        String registerCaptcha = jsonObject.getString("loginCaptcha");
        Result build = null;
        if(StringUtils.isBlank(captcha)) {
            build = Result.create().setMsg("系统异常，验证码未生成").setStatus(SystemConstant.ERROR).build();
        } else if(registerCaptcha == null) {
            build = Result.create().setMsg("验证码不能传入空值").setStatus(SystemConstant.ERROR).build();
        } else if(captcha.toLowerCase().equals(registerCaptcha.toLowerCase())) {
            removeSessionKey(session, SystemConstant.SESSION_KEY_OF_CAPTCHA);
            String userName = jsonObject.getString("userName");
            User currentUser = SessionUtil.getCurrentUser(session);
            if(currentUser != null) {
	            if(userName.equals(currentUser.getUserAccount()) || userName.equals(currentUser.getUserEmail())) {
	            	build = Result.create().setMsg("请不要重复登录").setStatus(SystemConstant.ERROR).build();
	            }
            } else {
            	String userPwd = jsonObject.getString("userPwd");
                User result = userService.findByUserAccountOrEmail(userName);
                if(result != null) {
                    String userSalt = result.getUserSalt();
                    String dbPassword = result.getUserPwd();
                    if(EncryptUtil.compare(userPwd, dbPassword, userSalt)) {
                        setSession(session, SystemConstant.SESSION_KEY_OF_USER, result);
                        
                        Boolean rememberMe = jsonObject.getBoolean("rememberMe");
                        if(rememberMe) {
                            String token = DESUtil.getEncryptString(result.getUserAccount() + DESUtil.SPLITER + result.getUserPwd());
                            build = Result.create().setMsg("登录成功").setStatus(SystemConstant.SUCCESS).setObject(token).build();
                        } else {
                            build = Result.create().setMsg("登录成功").setStatus(SystemConstant.SUCCESS).setObject("").build();
                        }
                        
                    } else {
                        build = Result.create().setMsg("用户名或者密码错误").setStatus(SystemConstant.FAILED).build();
                    }
                } else {
                    build = Result.create().setMsg("账号不存在").setStatus(SystemConstant.ERROR).build();
                }
            }
        } else {
            build = Result.create().setMsg("验证码错误").setStatus(SystemConstant.FAILED).build();
        }
        return build;
    }
    
    /**
     * <pre>
     * <b>desc:</b> 用户注册 
     * <b>auth:</b> 何家明
     * <b>date:</b> 2018年6月6日 上午10:39:17
     * </pre>
     * @param json
     * @param session
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public Result register(@RequestBody String json, HttpSession session) {
        String captcha = getSessionString(session, SystemConstant.SESSION_KEY_OF_CAPTCHA);
        JSONObject jsonObject = convertJsonToObject(json);
        String registerCaptcha = jsonObject.getString("registerCaptcha");
        Result build = null;
        if(StringUtils.isBlank(captcha)) {
            build = Result.create().setMsg("系统异常，验证码未生成").setStatus(SystemConstant.ERROR).build();
        } else if(registerCaptcha == null) {
            build = Result.create().setMsg("验证码不能传入空值").setStatus(SystemConstant.ERROR).build();
        } else if(captcha.toLowerCase().equals(registerCaptcha.toLowerCase())) {
            removeSessionKey(session, SystemConstant.SESSION_KEY_OF_CAPTCHA);
            String userName = jsonObject.getString("userName");
            String userPwd = jsonObject.getString("userPwd");
            int rows = userService.register(userName, userPwd);
            if(rows == 1) {
                User result = userService.findByUserAccountOrEmail(userName);
                setSession(session, SystemConstant.SESSION_KEY_OF_USER, result);
                build = Result.create().setMsg("注册成功").setStatus(SystemConstant.SUCCESS).build();
            } else if(rows == -1) {
                build = Result.create().setMsg("该账号已存在").setStatus(SystemConstant.FAILED).build();
            } else {
                build = Result.create().setMsg("后台异常").setStatus(SystemConstant.ERROR).build();
            }
        } else {
            build = Result.create().setMsg("验证码错误").setStatus(SystemConstant.FAILED).build();
        }
        return build;
    }
    
    /**
     * <pre>
     * <b>desc:</b> 登出 
     * <b>auth:</b> ex-hejm
     * <b>date:</b> 2018年6月8日 下午3:07:05
     * </pre>
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(SystemConstant.SESSION_KEY_OF_USER);
        return "redirect:/";
    }
    
    /**
     * <pre>
     * <b>desc:</b> 验证用户邮箱 
     * <b>auth:</b> ex-hejm
     * <b>date:</b> 2018年6月8日 下午4:11:10
     * </pre>
     * @param session
     * @return
     */
    @RequestMapping("/validateEmail")
    public void validateEmail(HttpSession session) {
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                EmailUtil.sendSimpleEmail();
            }
        });
    }
}
